<template>
  <div>
    <lemon-imui :user='this.user'
                ref='IMUI'
                @pull-messages='handlePullMessages'
                @send='handleWsSend'>
      <el-button plain icon="el-icon-delete" type="danger"
                 slot = 'editor-footer' @click = 'closeContact'>断开连接</el-button>
<!--      <div slot = 'cover' class = "size-icon">-->
<!--        <i class="el-icon-user">暂无访客</i>-->
<!--      </div>-->

    </lemon-imui>


  </div>
</template>

<script>
import EmojiData from "../../database/emoji.js";
import { MessageBox } from 'element-ui';
import global from '../../database/global.js'



export default {
  name: "chat",
  data(){
    return {
      user:{id:1,
            displayName:'June',
            avatar:'',}
    }
  },
  methods:{

    comment(contactName,chatToken){
  //评价输入弹窗
      MessageBox.prompt('请输入对\'' + contactName + '\'的评价：', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder:'评价内容',
        inputErrorMessage: '格式不正确'
      }).then(({ value }) => {
        this.$message({
          type: 'success',
          message: '评价成功'
        });
        const axios = require('axios').default;
        axios({
          method: 'post',
          url: '/chat/counselor-comment',
          data: {
            sessionId: chatToken,
            counselorFeedback: value,
            type:1
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消评价'
        });
      });


    },

    closeContact() {
      const { IMUI } = this.$refs;
      const contact = IMUI.getCurrentContact();
      MessageBox.confirm('是否断开与该联系人的连接?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const contactName = contact.displayName
        const contactId = contact.id
        const chatToken = global.mapInv(contactId)
        IMUI.removeContact(contactId)
        const axios = require('axios')

        axios.get('/chat/end-vc-session?chatToken=' + chatToken)
            .then(function (response) {
              // 处理成功情况
              console.log(response);
            })
            .catch(function (error) {
              // 处理错误情况
              console.log(error);
            })
            .then(function () {
              // 总是会执行
            });

        this.$message({
          type: 'success',
          message: '断开成功!'
        });
        global.map.delete(chatToken)
        global.mapInv.delete(contactId)
        this.comment(contactName,chatToken)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消断开'
        });
      });

    },

    handlePullMessages(contact, next) {
      //从后端请求消息数据，包装成下面的样子
      const messages = [{
        id: '唯一消息ID',
        status: 'succeed',
        type: 'text',
        sendTime: 1566047865417,
        content: '你什么才能对接完？',
        toContactId: contact.id,
        fromUser:this.user
      }]
      //将第二个参数设为true，表示已到末尾，聊天窗口顶部会显示“暂无更多消息”，不然会一直转圈。
      next(messages,true);
    },
    handleWsSend(message, next, file) {
      const { IMUI } = this.$refs;
      const contact = IMUI.getCurrentContact()
      //调用你的消息发送业务接口
      global.ws.send(JSON.stringify({
        content : message.content,
        chatToken : global.mapInv.get(contact.id)
      }));
      //执行到next消息会停止转圈，如果接口调用失败，可以修改消息的状态 next({status:'failed'});
      if (global.ws.readyState === WebSocket.OPEN)
        next();
      else
        next({status:'failed'});
    },

    handleWsOpen(e){
      const { IMUI } = this.$refs;
      const chatToken = (e.data)["chatToken"];
      const toUserKey = (e.data)["toUserKey"];
      global.map.set(chatToken,toUserKey)
      global.mapInv.set(toUserKey,chatToken)
      const contact = {
        id: toUserKey,
        displayName:'',
        avatar:'',
        index:'',
        unread: 1,
        //最近一条消息的内容，如果值为空，不会出现在“聊天”列表里面。
        //lastContentRender 函数会将 file 消息转换为 '[文件]', image 消息转换为 '[图片]'，对 text 会将文字里的表情标识替换为img标签,
        lastContent: IMUI.lastContentRender({type:'event',content:'该访客向你发起新的会话'}),
        //最近一条消息的发送时间
        lastSendTime: Date.now()
      }
      IMUI.appendContact(contact)
    },
    handleWsClose(e){
      const { IMUI } = this.$refs;
      const chatToken = e.data;
      const contactId = global.map.get(chatToken)
      const contactName = global.userMap.get(contactId)
      this.$alert('访客\'' + contactName  + '\'已断开连接', '提示', {
        confirmButtonText: '评价该访客',
        callback: action => {
          this.$message({
            type: 'info',
            message: `action: ${ action }`
          });
        }
      });
      IMUI.removeContact(contactId);
      global.map.delete(chatToken)
      global.mapInv.delete(contactId)
      this.comment(contactName,chatToken);
    },
    handleWsError(e){
      let info = e.data
      console.log(info)
    },
    handleWsMessage(e){
      const { IMUI } = this.$refs;
      const con = (e.data)["content"];
      const fromToken = (e.data)["from"];
      let msg = {
        id: this.getRandomArbitrary(0,100000),
        status: 'succeed',
        type: 'text',
        sendTime: Date.now(),
        content: con,
        toContactId: global.map.get(fromToken),
        fromUser:this.user
      }
      IMUI.appendMessage(msg,true)
    },
    getRandomArbitrary(min, max){
      return Math.random() * (max - min) + min;
    }
},
  mounted(){
    const { IMUI } = this.$refs;

    //初始化表情包。
    IMUI.initEmoji(EmojiData);

    //初始化用户信息
    // this.user.displayName = localStorage.getItem('username')

    global.ws.addEventListener('chatToken',this.handleWsOpen.bind(this),false);
    global.ws.addEventListener('commentNotify',this.handleWsClose.bind(this),false);
    global.ws.addEventListener('boringNotify',this.handleWsClose.bind(this),false);
    global.ws.addEventListener('err',this.handleWsError.bind(this),false);
    global.ws.addEventListener('message',this.handleWsMessage.bind(this),false);

    //从后端请求联系人数据，包装成下面的样子
    const contacts = [{
      id: 2,
      displayName: '丽安娜',
      avatar:'',
      index:'L',
      unread: 0,
      //最近一条消息的内容，如果值为空，不会出现在“聊天”列表里面。
      //lastContentRender 函数会将 file 消息转换为 '[文件]', image 消息转换为 '[图片]'，对 text 会将文字里的表情标识替换为img标签,
      lastContent: IMUI.lastContentRender({type:'text',content:'你在干嘛呢？'}),
      //最近一条消息的发送时间
      lastSendTime: 1566047865417,
    }];
    IMUI.initContacts(contacts);
  }
}
</script>

<style scoped>
.size-icon{
  margin-top: 180px;
  vertical-align: middle;
  font-size: 80px;
  text-align: center;
}
</style>